package com.common.tool;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedInputStream;
import java.io.IOException;

public class RequestTool {

    public static String result(HttpServletRequest request) throws IOException {
        // 得到请求体流 读取请求体信息
        ServletInputStream inputStream = request.getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        StringBuilder builder = new StringBuilder();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = bufferedInputStream.read(buffer)) != -1) {
            builder.append(new String(buffer, 0, length));
        }
        return builder.toString();
    }

    public static<T> T result(HttpServletRequest request,Class<T> tClass) throws IOException {
        String result = result(request);
        if (StrUtil.isEmptyIfStr(result)){
            return null;
        }
        return JSONUtil.toBean(result,tClass);
    }
}
